<!--
 * @Description: 基础页面布局
 * @Author: seadon
 * @LastEditors: zhaoxiaoyang zhaoxiaoyang@byteluck.com
 * @Date: 2021-07-07 11:19:07
 * @LastEditTime: 2023-08-14 15:27:52
-->
<template>
	<a-layout class="pok-basic-layout">
		<a-layout-header
			v-if="showHeader"
			class="header-container"
			:class="{ 'container-scroll': isScroll }"
		>
			<!-- Logo -->
			<div v-if="tenantDetail.blue_logo_url" class="header-logo">
				<router-link :to="defaultRouter">
					<img :src="tenantDetail.blue_logo_url" />
				</router-link>
			</div>
			<!-- 菜单 -->
			<a-menu
				v-if="route.path !== '/welcome'"
				class="menu-box"
				mode="horizontal"
				:overflowed-indicator="overflowedIndicator"
				@click="handleChangeRoute"
			>
				<a-menu-item
					v-for="item in menus"
					:key="
						item.mode ? item.menu_id : `${item.access_path}||${item.menu_id}`
					"
					class="menu-box-item"
					:class="{ 'menu-active': selectedKeys === item.menu_id }"
				>
					<div style="display: flex">
						<div class="item-before">
							<img src="@/assets/images/menu_left.svg" />
						</div>
						<div class="item-text">
							<EllipsisTooltip :title="item.menu_name" />
						</div>
						<div class="item-after">
							<img src="@/assets/images/menu_right.svg" />
						</div>
					</div>
				</a-menu-item>
			</a-menu>
			<!-- 右侧布局 -->
			<pok-header-right
				:is-outside-org="isOutsideOrg"
				:org-detail="orgDetail"
				:tenant-detail="tenantDetail"
				@showChangeOrg="showChangeOrg"
			>
				<template #changeOrg>
					<div v-if="OrgListIsShow" class="org-mask">
						<changeOrg
							:is-outside-org="isOutsideOrg"
							:org-detail="orgDetail"
							:label-id="''"
							@showChangeOrg="showChangeOrg"
						>
							<template #changeOrgTitle>
								<p class="change-org-title">
									<span>组织切换</span>
									<span @click="showChangeOrg(false)">×</span>
								</p>
							</template>
						</changeOrg>
					</div>
				</template>
			</pok-header-right>
		</a-layout-header>
		<!-- <div class="expiration-reminder" v-if="expirationVisible">
			<i class="low-code iconjinggaomian"></i>
			<span>
				您目前的产品版本将在 {{ expiryDateArr[0] }} 年 {{ expiryDateArr[1] }} 月
				{{ expiryDateArr[2] }} 日到期，若需要延期，请联系 400-1818-187
			</span>
			<div @click="handleCloseExpiration">关闭</div>
		</div> -->
		<a-layout-content class="content-container">
			<div class="content-body">
				<router-view></router-view>
			</div>
		</a-layout-content>
	</a-layout>
</template>
<script setup lang="ts">
import {
	ref,
	reactive,
	computed,
	unref,
	onMounted,
	h,
	watch,
	onUpdated,
} from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useStore } from 'vuex'
import { find, invert } from 'lodash'
import { routerMapList } from '@/constant/menu'
import PopupVideo from '@/entry_desktop/components/PopupVideo'
import EllipsisTooltip from '@/entry_desktop/components/EllipsisTooltip'
import PokHeaderRight from '@/entry_desktop/components/HeaderRight'
import changeOrg from '@/entry_desktop/components/ChangeOrg/changeOrg.vue'
import { apiInit } from '@/services'
import { useEventListener } from '@/hooks/useEventListener'
import { isSticky, client, isEmpty, path } from '@/utils'
import './index.less'
const route = useRoute()
const store = useStore()
const isOutsideOrg = computed(
	() => store.state.userInfo.org_type === 'EXTERNAL'
)

const router = useRouter()
const api = apiInit()
const defaultRouter = reactive({ name: 'Layout' })
const menus = ref()
const OrgListIsShow = ref(false)
const orgDetail = computed(() => store.state.userInfo)
const showChangeOrg = (val: boolean) => {
	setTimeout(() => {
		document.body.style.overflow = val ? 'hidden' : 'auto'
	}, 500)
	OrgListIsShow.value = val
}
const showHeader = computed(() => {
	// 业务逻辑如下，开启启动器时使用运行态的头部，页面从运行态嵌入，关闭启动器时保持原有逻辑，头部使用portal本身的头部
	const hasAppLauncher = store.state.tenant?.tenant_auth?.app_launcher !== 1
	// const hash = window.location.hash
	// let noheader = ['#/home', '#/', ''].includes(hash)
	// if (hash.indexOf('turnOnTheStarter') > -1) {
	// 	noheader = true
	// }
	return hasAppLauncher
})

const fetchMenuList = async () => {
	const { code, data } = await api.default.ListMenuPrivateV2POST({})
	if (code === '000000') {
		menus.value = (data as unknown[])?.filter((item: any) => {
			return item.menu_id !== 'applicationcenter'
		})
		defaultRouter.name =
			routerMapList[find(unref(menus), 'mode')?.menu_id] ?? 'Layout'

		if (route.name === 'Layout') {
			router.push(defaultRouter)
		}
	}
}

const selectedKeys = computed(() => invert(routerMapList)[route.name as string])

// 菜单路由变更
const handleChangeRoute = ({ key }: layout.ChangeRouteParam) => {
	if (key === 'home') {
		const hasAppLauncher = store.state.tenant?.tenant_auth?.app_launcher === 1
		if (hasAppLauncher === true) {
			window.location.href = path.getFullPath('/apps/desktop/multipleTabs')
		}
	}
	if (/\|\|/.test(key)) {
		const accessUrl = key.split('||')[0]
		//由于钉钉啥的内置浏览器，版本比较低。设计态直接弹出客户端
		const isApplicationManage = key.split('||')[1] === 'applicationmanage'
		if (isApplicationManage) {
			window.open(accessUrl)
		} else {
			client.openWindow(accessUrl)
		}
	} else {
		// selectedKeys.value = [key]
		router.push({ name: routerMapList[key] })
	}
}

// 获取租户信息
let tenantDetail: Recordable<any> = {}
let expiryDateArr: string[]
let stillHaveDays: number
// const expirationReminder = ref(Cookies.get('expirationReminder'))

// 产品需求：重新进入流程中心，不记忆流程中心的tab定位
localStorage.removeItem('activeProcessKey')

watch(
	() => store.state.tenant,
	tenant => {
		if (!isEmpty(tenant)) {
			tenantDetail = tenant || {}
			// const todayMoment = moment()
			// const expiryTimeMoment = moment(tenantDetail.expiry_time)
			// if (expiryTimeMoment) {
			// 	stillHaveDays = expiryTimeMoment.diff(todayMoment, 'day')
			// 	expiryDateArr = expiryTimeMoment.format('YYYY/M/D').split('/')
			// }
		}
	},
	{
		immediate: true,
	}
)

// const expirationVisible = computed(
// 	() => !unref(expirationReminder) && stillHaveDays <= 15
// )

// 关闭到期窗口
// const handleCloseExpiration = () => {
// 	const today = new Date()
// 	const tomorrow = new Date(
// 		`${today.getFullYear()}-${today.getMonth() + 1}-${today.getDate() + 1}`
// 	)

// 	expirationReminder.value = '1'
// 	Cookies.set('expirationReminder', '1', { expires: tomorrow })
// }
const isScroll = ref(false)
const isStick = isSticky()
const overflowedIndicator = computed(() =>
	h('i', { class: 'low-code icongengduo1 menu-icon' })
)

onMounted(() => {
	useEventListener({
		name: 'scroll',
		wait: 0,
		listener: () => {
			if (!isStick) {
				return
			}
			const scrollTop =
				window.pageYOffset ||
				document.documentElement.scrollTop ||
				document.body.scrollTop

			isScroll.value = scrollTop > 1
		},
	})
	fetchMenuList()

	window.addEventListener('message', function (event) {
		if (event.data.sapp_type === 'processcenter') {
			sessionStorage.setItem(
				'processcenter_name',
				event.data.processcenter_name
			)
		}
	})
})
</script>
<style lang="less" scoped>
.org-mask {
	display: flex;
	justify-content: center;
	align-items: center;
	position: fixed;
	left: 0;
	top: 0;
	z-index: 20;
	height: 100vh;
	width: 100vw;
	background: rgba(94, 108, 157, 0.5);
	.change-org-title {
		padding: 24px 24px 16px 24px;
		// background: var(--bl-brand-c);
		background: #fff;
		display: flex;
		justify-content: space-between;
		align-items: center;
		border-top-left-radius: 8px;
		border-top-right-radius: 8px;
		span {
			color: #1f2329;
		}
		span:first-child {
			font-family: 'PingFang SC';
			font-style: normal;
			font-weight: 500;
			font-size: 16px;
			line-height: 18px;
		}
		span:last-child {
			cursor: pointer;
			font-size: 24px;
			line-height: 18px;
			margin-top: -2px;
		}
	}
}
:deep {
	.content-container:not(:has(.home-header)) {
		margin-top: 13px;
		.home-content {
			margin-top: 0;
		}
	}
	.ant-menu-submenu-horizontal .ant-menu-submenu-title {
		line-height: 55px;
	}
	.ant-menu-horizontal:not(.ant-menu-dark) > .ant-menu-item-selected {
		color: var(--bl-n600-c);
	}
	.ant-menu-horizontal:not(.ant-menu-dark) > .ant-menu-item:hover {
		color: var(--bl-brand-c);
	}
}
</style>
